const { response } = require('express');
var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient
var config = require('../config/db')
var passport = require('passport');
const { MongoDBNamespace } = require('mongodb');
const mongdb = require('mongodb')
const jwt = require('jsonwebtoken')

/*显示订单数据 */
router.get('/getOrders',passport.authenticate('jwt',{session:false}),async function(req,res,next){
  let client = await MongoClient.connect(config.url) //获取数据库连接对象
  let db = client.db()
  let orders = await db.collection('orders').find({userId:req.user._id}).sort({'addTime':-1}).toArray() 
  if(orders.length >= 0){
      res.json({code:200, message:'ok', data: orders });
  }else{
      res.json({code:200, message:'error'});
  }
});

router.post('/addOrder',passport.authenticate('jwt',{session:false}),async function(req,res,next){
  let order = req.body.order//获取需要添加的订单商品信息
  let client = await MongoClient.connect(config.url) //获取数据库连接对象
  let db = client.db()
  let newOrder = {
      "userId":req.user._id,
      "products":order.products,
      "totalPrice":order.totalPrice,
      "addTime":new Date(),
      "state":0 ,//0待支付 1已支付 2待评价 3已评价
      "comment":null,
  }
  let results = await db.collection('orders').insertOne(newOrder) //执行添加订单的操作
  //判断是否添加成功
  if(results.acknowledged){
      let orders = await db.collection('orders').find({ userId: req.user._id}).sort({'addTime':-1}).toArray()
      console.log('orders:',orders[0]._id)
      res.json({code:200,message:'ok', data: orders[0]._id });
  }else{
      res.json({code:200,message:'error'});
  }
});

//支付、并修改订单状态
router.put('/editOrder',passport.authenticate('jwt',{session:false}),async function(req,res,next){
  let orderId = req.body.params.orderId//获取需要添加的订单商品信息
  let state =req.body.params.state
  let client = await MongoClient.connect(config.url) //获取数据库连接对象
  let db = client.db()
  console.log('orderId',orderId)
  let results = await db.collection('orders').updateOne({ _id: new mongdb.ObjectId(orderId) },{ $set: {state }} )
  //判断是否修改成功
  if(results.acknowledged){
      console.log('results:',results)
      res.json({code:200,message:'ok'});
  }else{
      res.json({code:200,message:'error'});
  }
});

//添加评论
router.put('/addOrderComment',passport.authenticate('jwt',{session:false}),async function(req,res,next){
    let orderId = req.body.params.orderId//获取需要添加的订单商品信息
    let content =req.body.params.comment
    let client = await MongoClient.connect(config.url) //获取数据库连接对象
    let db = client.db()
    let comment = {}
    comment.connect = content
    comment.commentTime = new Date()
    let results = await db.collection('orders').updateOne({ _id: new mongdb.ObjectId(orderId) },{ $set: {comment }} )
    //判断是否修改成功
    if(results.acknowledged){
        console.log('results:',results)
        res.json({code:200,message:'ok'});
    }else{
        res.json({code:200,message:'error'});
    }
  });

  //获取当前用户所有订单评价信息
  router.get('/getOrdersComment',passport.authenticate('jwt',{session:false}),async function(req,res,next){
    let client = await MongoClient.connect(config.url) //获取数据库连接对象
    let db = client.db()
    let orders = await db.collection('orders').find({userId:req.user._id,comment:{$ne:null}}).sort({'addTime':-1}).toArray() 
    if(orders.length >= 0){
        res.json({code:200, message:'ok', data: orders });
    }else{
        res.json({code:200, message:'error'});
    }
  });

module.exports = router;